﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using NetCoreCMS.Common;
using NetCoreCMS.IServices;
using NetCoreCMS.Models;
using Newtonsoft.Json.Linq;

namespace NetCoreCMS.Web.Areas.Admin.Controllers.Article
{
    public class Spec_ListController : ManageController
    {
        private const string WEB_VIEW = "~/Areas/Admin/Views/Article/spec_list.cshtml";
        protected int totalCount;
        protected int page;
        protected int pageSize;

        protected string keywords = string.Empty;
        public IArticle_specService _article_spec { get; set; }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (filterContext.Result != null)
                return;
            ChkAdminLevel("article_2_spec", CMSEnums.ActionEnum.View.ToString()); //检查权限
            ActionResult result = View(EDIT_RESULT_VIEW);
            this.keywords = Request.Query["keywords"];
            int.TryParse(Request.Query["page"],out this.page);
            int.TryParse(Request.Query["pagesize"], out this.pageSize);//每页数量
            if (this.pageSize > 0)
            {
                Response.Cookies.Append("article_spec_page_size", this.pageSize.ToString());
            }
            else
            {
                this.pageSize = GetPageSize(10);
            }
            ViewBag.Keywords = this.keywords;
            ViewBag.PageSize = this.pageSize;
            ViewBag.Page = this.page.ToString();
        }

        // GET: /admin/Spec_List/
        public ActionResult Index()
        {
            RptBind("where parent_id=0 " + CombSqlTxt(keywords), "sort_id asc,id desc");
            return View(WEB_VIEW);
        }

        [HttpPost]
        /// <summary>
        /// 提交保存
        /// </summary>
        /// <returns></returns>
        public ActionResult SubmitSave(string json)
        {
            ChkAdminLevel("article_2_spec", CMSEnums.ActionEnum.Edit.ToString()); //检查权限
            JObject jobject = JObject.Parse(json);
            JToken record = jobject["list"];
            foreach (JToken item in record)
            {
                int id;
                if (!int.TryParse(item["id"].ToString(), out id))
                    id = -1;
                int sortId;
                if (!int.TryParse(item["sortId"].ToString(), out sortId))
                    sortId = 99;
                _article_spec.UpdateField(id, "sort_id=" + sortId.ToString());
            }
            AddAdminLog(CMSEnums.ActionEnum.Edit.ToString(), "保存商品规格排序"); //记录日志
            string script = JscriptMsg("保存排序成功！", Utils.CombUrlTxt("index", "keywords={0}", this.keywords));
            return Content(script);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <returns></returns>
        public ActionResult SubmitDelete(string json)
        {
            ChkAdminLevel("article_2_spec", CMSEnums.ActionEnum.Delete.ToString()); //检查权限
            int sucCount = 0;
            int errorCount = 0;
            JObject jobject = JObject.Parse(json);
            JToken record = jobject["list"];
            int id;
            foreach (JToken item in record)
            {
                if (int.TryParse(item["id"].ToString(), out id))
                {
                    if (_article_spec.Delete(id))
                    {
                        sucCount += 1;
                    }
                    else
                    {
                        errorCount += 1;
                    }
                }
            }
            AddAdminLog(CMSEnums.ActionEnum.Delete.ToString(), "删除商品规格" + sucCount + "条，失败" + errorCount + "条"); //记录日志
            string script = JscriptMsg("删除规格成功" + sucCount + "条，失败" + errorCount + "条！", Utils.CombUrlTxt("index", "keywords={1}", this.keywords));
            return Content(script);
        }

        #region 数据绑定=================================
        private void RptBind(string _strWhere, string _orderby)
        {
            int.TryParse(Request.Query["page"], out this.page);
            this.page = this.page <= 0 ? 1 : this.page;
            var list = _article_spec.GetList(this.page, this.pageSize, _strWhere, _orderby, null);
            for (int i = 0; i < list.Count; i++)
            {
                var values= _article_spec.GetList("where parent_id=" + list[i].id);
                List<Article_spec_value> listvalue = new List<Article_spec_value>();
                foreach (var item in values)
                {
                    Article_spec_value model = new Article_spec_value();
                    model.id = item.id;
                    model.parent_id = item.parent_id;
                    model.img_url = item.img_url;
                    model.sort_id = item.sort_id;
                    model.title = item.title;
                    listvalue.Add(model);
                }
                list[i].values = listvalue;
            }
            ViewData["list"] = list;
            this.totalCount = _article_spec.RecordCount(_strWhere);
            string pageUrl = Utils.CombUrlTxt("index", "keywords={0}&page={1}", this.keywords, "__id__");
            ViewBag.PageContent = Utils.OutPageList(this.pageSize, this.page, this.totalCount, pageUrl, 8);
        }
        #endregion

        #region 组合SQL查询语句==========================
        protected string CombSqlTxt(string _keywords)
        {
            StringBuilder strTemp = new StringBuilder();            
            if (!string.IsNullOrEmpty(_keywords))
            {
                _keywords = _keywords.Replace("'", "");
                strTemp.Append(" and title like  '%" + _keywords + "%'");
            }

            return strTemp.ToString();
        }
        #endregion

        #region 返回每页数量=============================
        private int GetPageSize(int _default_size)
        {
            int _pagesize;
            if (int.TryParse(Request.Cookies["article_spec_page_size"], out _pagesize))
            {
                if (_pagesize > 0)
                {
                    return _pagesize;
                }
            }
            return _default_size;
        }
        #endregion
    }
}
